package homework.apiday07.exists01;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        System.out.println("正在连接服务端...");
        /**
         * 实例化Socket,就是与远端计算机建立连接的过程
         * 需要传入两个参数:
         * 1.服务端的IP地址,用于找到网络上对方的计算机
         * 2.服务端口,用于找到服务端计算机上的服务端应用程序
         */
        try {
            socket = new Socket("localhost",8088);
            System.out.println("服务端链接成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void start(){
        /**
         * 向服务端发送消息
         * Socket提供了一个重要方法:
         * 通过socket获取输出流写出的信息可以发送给服务端
         */
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out,StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);
            Scanner scan = new Scanner(System.in);
            while (true){
                String line = scan.nextLine();
                if ("homework_talkroom".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
